package com.yunxi.poc.starbucks.service.impl;

import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yunxi.poc.starbucks.entity.Tb1StoreData;
import com.yunxi.poc.starbucks.mapper.Tb1StoreDataMapper;
import com.yunxi.poc.starbucks.service.ITb1StoreDataService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.*;
import org.springframework.http.converter.StringHttpMessageConverter;
import org.springframework.stereotype.Service;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;

import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author shiyuan.xlc
 * @since 2021-08-12
 */
@Service
public class Tb1StoreDataServiceImpl extends ServiceImpl<Tb1StoreDataMapper, Tb1StoreData> implements ITb1StoreDataService {

    private final static Logger logger = LoggerFactory.getLogger(Tb1StoreDataServiceImpl.class);

    @Override
    public List<String> searchGeoShape(double longitude, double latitude) {
        RestTemplate restTemplate = new RestTemplate();

        MultiValueMap<String, String> header = new LinkedMultiValueMap<>();
        header.add(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE);

        String queryStr = "{\n" +
                "  \"size\": 100,\n" +
                "  \"query\": {\n" +
                "    \"bool\": {\n" +
                "      \"must\": {\n" +
                "        \"match_all\": {}\n" +
                "      },\n" +
                "      \"filter\": {\n" +
                "        \"geo_shape\": {\n" +
                "          \"location\": {\n" +
                "            \"shape\": {\n" +
                "              \"type\": \"point\",\n" +
                "              \"coordinates\": [" + longitude + "," + latitude + "]\n" +
                "            },\n" +
                "            \"relation\": \"intersects\"\n" +
                "          }\n" +
                "        }\n" +
                "      }\n" +
                "    }\n" +
                "  }\n" +
                "}";

        JSONObject mapping = JSONUtil.parseObj(queryStr);
        HttpEntity<MultiValueMap> mappingReq = new HttpEntity(mapping, header);
        restTemplate.getMessageConverters().set(1, new StringHttpMessageConverter(StandardCharsets.UTF_8));

        ResponseEntity<JSONObject> mappingRes = restTemplate.exchange(
                "http://10.92.208.3:9200/store_geo_shape/_search?pretty&filter_path=hits.total,hits.hits._source.store_id",
                HttpMethod.POST,
                mappingReq,
                JSONObject.class);

        if (HttpStatus.OK.value() != mappingRes.getStatusCodeValue()) {
            return new ArrayList<>();
        }

        Integer hitsTotal = Objects.requireNonNull(mappingRes.getBody()).getByPath("hits.total", Integer.class);
        if (0 == hitsTotal) {
            return new ArrayList<>();
        }

        List<String> ids = new ArrayList<>();
        for (int i = 0; i < hitsTotal; i++) {
            ids.add(mappingRes.getBody().getByPath("hits.hits[" + i + "]._source.store_id", String.class));
        }

        return ids;
    }
}
